package com.ruoyi.gouhuoruku.controller;


import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.ruoyi.cangku.service.ICangkuService;
import com.ruoyi.common.core.text.Convert;
import com.ruoyi.gouhuoruku.domain.GouhuoRuku2;
import com.ruoyi.kucunpandian.domain.Kucunpandian;
import com.ruoyi.kucunpandian.service.IKucunpandianService;
import com.ruoyi.piliangruku.service.IPiliangRukuService;
import com.ruoyi.shangpinxinxi.domain.Shangpinxinxi;
import com.ruoyi.shangpinxinxi.domain.Shangpinxinxi2;
import com.ruoyi.shangpinxinxi.service.IShangpinxinxiService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.gouhuoruku.domain.GouhuoRuku;
import com.ruoyi.gouhuoruku.service.IGouhuoRukuService;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

import javax.servlet.http.HttpServletRequest;

/**
 * 购货入库Controller
 * 
 * @author ruoyi
 * @date 2023-01-10
 */
@Controller
@RequestMapping("/gouhuoruku/rukuTest")
public class GouhuoRukuController extends BaseController
{
    private String prefix = "gouhuoruku/rukuTest";

    @Autowired
    private IGouhuoRukuService gouhuoRukuService;
    @Autowired
    private IKucunpandianService cangkupandianService;
    @Autowired
    private IPiliangRukuService piliangRukuService;
    @Autowired
    private IShangpinxinxiService shangpinxinxiService;
    @Autowired
    private ICangkuService cangkuService;

    @RequiresPermissions("gouhuoruku:rukuTest:view")
    @GetMapping()
    public String rukuTest()
    {
        return prefix + "/rukuTest";
    }

    /**
     * 查询购货入库列表
     */
    @RequiresPermissions("gouhuoruku:rukuTest:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(HttpServletRequest request, GouhuoRuku gouhuoRuku)
    {
        startPage();
        String a = request.getSession().getAttribute("QuanXian").toString();
        if (a.equals("0") && (gouhuoRuku == null || gouhuoRuku.getGouhuoCangku().equals(""))) {
            List<GouhuoRuku> namee2cangku = gouhuoRukuService.selectAllGouhuoRukuList(request.getSession().getAttribute("name4user").toString());

            return getDataTable(namee2cangku);
        }else {
            startPage();
            List<GouhuoRuku> list = gouhuoRukuService.selectGouhuoRukuList(gouhuoRuku);

            /*String s=list.toString();
            JSONObject jsonObject= JSON.parseObject(s);
            System.out.println(jsonObject+"----------------------------------------------------------------------------------------------------------");
            */
            return getDataTable(list);

        }
    }

/*    void post(GouhuoRuku gouhuoRuku){
        List<GouhuoRuku> list = gouhuoRukuService.selectGouhuoRukuList(gouhuoRuku);
        for (int i = 0; i < list.size(); i++) {
            System.out.println(list.get(i)+"----------------------------------------------------------------------------------------------------------");
        }
    }*/

    /**
     * 导出购货入库列表
     */
    @RequiresPermissions("gouhuoruku:rukuTest:export")
    @Log(title = "购货入库", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(HttpServletRequest request,GouhuoRuku gouhuoRuku)
    {
        String a = request.getSession().getAttribute("QuanXian").toString();
        if (a.equals("1")) {
            List<GouhuoRuku> list = gouhuoRukuService.selectGouhuoRukuList(gouhuoRuku);
            ExcelUtil<GouhuoRuku> util = new ExcelUtil<GouhuoRuku>(GouhuoRuku.class);
            return util.exportExcel(list, "购货入库数据");
        }
        else {
            List<GouhuoRuku2> list = gouhuoRukuService.selectGouhuoRukuListAndQuanXian(gouhuoRuku);
            ExcelUtil<GouhuoRuku2> util = new ExcelUtil<GouhuoRuku2>(GouhuoRuku2.class);
            return util.exportExcel(list, "购货入库数据");
        }
    }

    /**
     * 新增购货入库
     */
    @GetMapping("/add")
    public String add()
    {
        return prefix + "/test";
    }

    /**
     * 新增保存购货入库
     */
    @RequiresPermissions("gouhuoruku:rukuTest:add")
    @Log(title = "购货入库", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(GouhuoRuku gouhuoRuku)
    {
        Kucunpandian cangkupandian = new Kucunpandian();
        if (gouhuoRuku.getGouhuoCangku().contains("_")) {
            cangkupandian.setCangkuName(gouhuoRuku.getGouhuoCangku().split("_")[0]);
        }else {cangkupandian.setCangkuName(gouhuoRuku.getGouhuoCangku()); }

        String numstr = gouhuoRukuService.selectGouhuoDanhaoByLastOne();
        int num;
        if (numstr == null || numstr.equals("")) {
            num = 1;
        }else {
            num = Integer.parseInt(numstr)+1;
        }
        String b = String.valueOf(num);
        if (String.valueOf(num).length() < 8) {
            int a = 8-String.valueOf(num).length();
            for (int j = 0; j < a; j++) {
                b="0" + b;
            }
        }
        gouhuoRuku.setGouhuoDanhao(b);
        cangkupandian.setGoodId(gouhuoRuku.getGoodId());

        Shangpinxinxi shangpinxinxi = shangpinxinxiService.selectShangpinxinxiByBianHao(gouhuoRuku.getGoodId());
        cangkupandian.setGoodName(shangpinxinxi.getShangpinName());
        cangkupandian.setGoodSpecification(shangpinxinxi.getShangpinGuige());
        cangkupandian.setShangpinLeibie(shangpinxinxi.getShangpinLeibie());
        cangkupandian.setKuncun(gouhuoRuku.getShuliang().longValue());
        cangkupandian.setShangpinLeibie(gouhuoRuku.getShangpinLeibie());

        Double jiner=gouhuoRuku.getDijia()* gouhuoRuku.getShuliang();

        gouhuoRuku.setJiner(jiner);

        gouhuoRuku.setGoodName(shangpinxinxi.getShangpinName());
        gouhuoRuku.setGoodGuige(shangpinxinxi.getShangpinGuige());
        gouhuoRuku.setShangpinLeibie(shangpinxinxi.getShangpinLeibie());

        cangkupandianService.insertKucunpandian(cangkupandian);

        goodsinsert(gouhuoRuku);
        return toAjax(gouhuoRukuService.insertGouhuoRuku(gouhuoRuku));
    }

    private void goodsinsert(GouhuoRuku gouhuoRuku) {
        Shangpinxinxi goods = new Shangpinxinxi();
        goods.setShangpinId(gouhuoRuku.getGoodId());
        goods.setShangpinName(gouhuoRuku.getGoodName());
        goods.setShangpinGuige(gouhuoRuku.getGoodGuige());
        List<Shangpinxinxi> check = shangpinxinxiService.selectShangpinxinxiList(goods);
        if (check.size() == 0) {
            shangpinxinxiService.insertShangpinxinxi(goods);
        }
    }

    /**
     * 修改购货入库
     */
    @RequiresPermissions("gouhuoruku:rukuTest:edit")
    @GetMapping("/edit/{id}")
    public String edit(@PathVariable("id") Long id, ModelMap mmap)
    {

        GouhuoRuku gouhuoRuku = gouhuoRukuService.selectGouhuoRukuById(id);
        mmap.put("gouhuoRuku", gouhuoRuku);
        return prefix + "/edit";
    }

    /**
     * 修改保存购货入库
     */
    @RequiresPermissions("gouhuoruku:rukuTest:edit")
    @Log(title = "购货入库", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(GouhuoRuku gouhuoRuku)
    {
        Kucunpandian cangkupandianList =
                cangkupandianService.selectCangkupandianByGoodIdAndCangKuNameAndGoodName(gouhuoRuku.getGoodId(),gouhuoRuku.getGouhuoCangku(),gouhuoRuku.getGoodName());

        Double oldKuCun = gouhuoRukuService.selectGouhuoRukuById(gouhuoRuku.getId()).getShuliang();

        Long kucun = cangkupandianList.getKuncun();

        double newKuCun = kucun+(gouhuoRuku.getShuliang()-oldKuCun);

        cangkupandianList.setKuncun(new Double(newKuCun).longValue());

        cangkupandianService.updateKucunpandian(cangkupandianList);

        Double jiner=gouhuoRuku.getDijia()* gouhuoRuku.getShuliang();
        gouhuoRuku.setJiner(jiner);
        int a = gouhuoRukuService.updateGouhuoRuku(gouhuoRuku);
        return toAjax(gouhuoRukuService.updateGouhuoRuku(gouhuoRuku));
    }

    /**
     * 删除购货入库
     */
    @RequiresPermissions("gouhuoruku:rukuTest:remove")
    @Log(title = "购货入库", businessType = BusinessType.DELETE)
    @PostMapping( "/remove")
    @ResponseBody
    public AjaxResult remove(String ids)
    {
        if (!ids.contains(",")) {
            kucunSet(ids);
        }else {
            String[] idlist = Convert.toStrArray(ids);
            for (String s:idlist) {
                kucunSet(s);
            }
        }
        return toAjax(gouhuoRukuService.deleteGouhuoRukuByIds(ids));
    }

    private void kucunSet(String s) {
        Long id = Long.valueOf(s);
        GouhuoRuku gouhuoRuku = gouhuoRukuService.selectGouhuoRukuById(id);
        Kucunpandian cangkupandian = new Kucunpandian();

        cangkupandian.setCangkuName(gouhuoRuku.getGouhuoCangku());
        cangkupandian.setGoodId(gouhuoRuku.getGoodId());
        cangkupandian.setGoodName(gouhuoRuku.getGoodName());
        cangkupandian.setGoodSpecification(gouhuoRuku.getGoodGuige());

        Kucunpandian kucunpandian = cangkupandianService.selectCangkupandianByGoodIdAndCangKuNameAndGoodName(gouhuoRuku.getGoodId(),gouhuoRuku.getGouhuoCangku(),gouhuoRuku.getGoodName());
        cangkupandian.setId(kucunpandian.getId());
        cangkupandian.setShangpinLeibie(gouhuoRuku.getShangpinLeibie());
        cangkupandian.setKuncun(kucunpandian.getKuncun() - gouhuoRuku.getShuliang().longValue());

        cangkupandianService.updateKucunpandian(cangkupandian);

        goodsinsert(gouhuoRuku);
    }

    /**
     * 批量增加购货入库
     */
    @RequiresPermissions("gouhuoruku:rukuTest:inserts")
    @Log(title = "购货入库", businessType = BusinessType.INSERT)
    @PostMapping("/inserts")
    @ResponseBody
    public AjaxResult inserts(String msg) {
        List<GouhuoRuku> gouhuoRukuList = new ArrayList<>();
        List<String> danhaoList = new ArrayList<>();
        List<String> piliangdanhaoList = new ArrayList<>();
        int bo = 0;
        if (msg.lastIndexOf("@", 7) != -1) {
            String[] goho = msg.split("@");
            String danhaoStr = gouhuoRukuService.selectGouhuoDanhaoByLastOne();
            for (int i = 0; i < goho.length-1; i++) {
                if (danhaoStr == null||danhaoStr.equals("")) {
                    if (i == 0) {
                        String danhao = "00000001";
                        danhaoList.add(danhao);
                    }else {
                        String danhao2Str = danhaoList.get(i-1);
                        danHaoSet(danhao2Str, danhaoList);
                    }
                }else {
                    if (i == 0) {
                        danHaoSet(danhaoStr, danhaoList);
                    }else {
                        String danhao2Str = danhaoList.get(i-1);
                        danHaoSet(danhao2Str, danhaoList);
                    }
                }
            }
//            for (String massg :
//                    goho) {
//                msgChongZu(massg, gouhuoRukuList,danhaoList.get(i));
//            }
            for (int i = 1; i < goho.length; i++) {
                msgChongZu(goho[i], gouhuoRukuList,danhaoList.get(i-1),piliangdanhaoList);
            }
        } else {
            String danhaoStr = gouhuoRukuService.selectGouhuoDanhaoByLastOne();
            danHaoSet(danhaoStr, danhaoList);
            msgChongZu(msg, gouhuoRukuList, danhaoList.get(0),piliangdanhaoList);
        }
        for (int i = 0; i < gouhuoRukuList.size(); i++) {
            if (gouhuoRukuList.get(i) != null) {
                bo = gouhuoRukuService.insertGouhuoRuku(gouhuoRukuList.get(i));
                kucunMoreSet(gouhuoRukuList.get(i));
                piliangRukuService.deletePiliangRukuByGgouhuoDanhao(piliangdanhaoList.get(i));

                Shangpinxinxi goods = new Shangpinxinxi();
                goods.setShangpinId(gouhuoRukuList.get(i).getGoodId());
                goods.setShangpinName(gouhuoRukuList.get(i).getGoodName());
                goods.setShangpinGuige(gouhuoRukuList.get(i).getGoodGuige());
                if (shangpinxinxiService.selectShangpinxinxiList(goods) == null) {
                    shangpinxinxiService.insertShangpinxinxi(goods);
                }
            }
        }
        if (bo != -1) {
            return toAjax(bo);
        } else {
            return toAjax(-1);
        }
    }

    private void kucunMoreSet(GouhuoRuku go) {
        Kucunpandian kucunpandian = cangkupandianService.selectCangkupandianByGoodIdAndCangKuNameAndGoodName(
                go.getGoodId(), go.getGouhuoCangku(), go.getGoodName());
        if (kucunpandian != null) {
            Long kucun = kucunpandian.getKuncun();

            double newKuCun = kucun+(go.getShuliang());

            kucunpandian.setKuncun(new Double(newKuCun).longValue());
            cangkupandianService.updateKucunpandian(kucunpandian);
        }else {
            Kucunpandian kucunpandian1 = new Kucunpandian();

            kucunpandian1.setCangkuName(go.getGouhuoCangku().split("_")[0]);
            kucunpandian1.setGoodId(go.getGoodId());
            kucunpandian1.setGoodName(go.getGoodName());
            kucunpandian1.setGoodSpecification(go.getGoodGuige());
            kucunpandian1.setKuncun(go.getShuliang().longValue());
            kucunpandian1.setShangpinLeibie(go.getShangpinLeibie());

            cangkupandianService.insertKucunpandian(kucunpandian1);
        }
    }

    private static void msgChongZu(String msg, List<GouhuoRuku> gouhuoRukuList,String danhao,List<String> piiangdanhao) {
        try {
            if (msg.length() >= 1) {
                String[] msgs = msg.split(":");
                String fid = msgs[1].split(";")[0];
                piiangdanhao.add(fid);
                Date ghDate = new SimpleDateFormat("yyyy-MM-dd").parse(
                        msgs[2].split(";")[0]);
                String GjingShouRen = msgs[3].split(";")[0];
                String GCangKu = msgs[4].split(";")[0];
                String GShangpinId = msgs[5].split(";")[0];
                String GShangpinLeibie = msgs[6].split(";")[0];
                String GShangpinName = msgs[7].split(";")[0];
                String GShangpinGuige = msgs[8].split(";")[0];
                Double GShangpinShuLiang = Double.parseDouble(msgs[9].split(";")[0]);
                String GShangpinDanWei = msgs[10].split(";")[0];
                String b = msgs[11].split(";")[0];
                Double GShangpinDiJia = 0.0;
                if (!msgs[11].split(";")[0].equals("-")&&!msgs[11].split(";")[0].equals("")) {
                    GShangpinDiJia = Double.parseDouble(msgs[11].split(";")[0]);
                }

                double GShangpinDijiaZong = 0.0;String GFuKuanFangShi="",GShangpinBeiZhu="";
                if (msgs[11].contains("fzdi")) {
                    String str = msgs[12].split(";")[0];
                    if (str == null || str.equals("")||str.equals("-")) {
                        GShangpinDijiaZong = 0;
                    }else {
                        GShangpinDijiaZong = Double.parseDouble(msgs[12].split(";")[0]);
                    }
                    GFuKuanFangShi = msgs[13].split(">")[1].split("<")[0];
                    if (msgs[14].length() != 1 && msgs[14].contains(";")) {
                        GShangpinBeiZhu = msgs[14].split(";")[0];
                    }
                }else {
                    GFuKuanFangShi = msgs[12].split(">")[1].split("<")[0];
                    if (msgs[13].length() != 1 && msgs[13].contains(";")) {
                        GShangpinBeiZhu = msgs[13].split(";")[0];
                    }
                }



                GouhuoRuku gouhuoRuku = new GouhuoRuku();

                gouhuoRuku.setGouhuoDanhao(danhao);

                gouhuoRuku.setGouhuoDate(ghDate);
                gouhuoRuku.setGouhuoJingshouren(GjingShouRen);
                gouhuoRuku.setGouhuoCangku(GCangKu);
                gouhuoRuku.setGoodId(GShangpinId);
                gouhuoRuku.setShangpinLeibie(GShangpinLeibie);
                gouhuoRuku.setGoodName(GShangpinName);
                gouhuoRuku.setGoodGuige(GShangpinGuige);
                gouhuoRuku.setShuliang(GShangpinShuLiang);
                gouhuoRuku.setDanwei(GShangpinDanWei);
                gouhuoRuku.setDijia(GShangpinDiJia);
                gouhuoRuku.setZongbudijia(GShangpinDijiaZong);

                Double jiner=gouhuoRuku.getDijia()* gouhuoRuku.getShuliang();
                gouhuoRuku.setJiner(jiner);
                //gouhuoRuku.setJiner(GShangpinJinEr);
                gouhuoRuku.setPaymentMethod(GFuKuanFangShi);
                gouhuoRuku.setBeizhu(GShangpinBeiZhu);


                gouhuoRukuList.add(gouhuoRuku);
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }

    private static void danHaoSet(String danhaoStr, List<String> danhaoList) {
        int num = Integer.parseInt(danhaoStr)+1;
        String b = String.valueOf(num);
        if (b.length() < 8) {
            int a = 8-b.length();
            for (int j = 0; j < a; j++) {
                b="0"+b;
            }
        }
        danhaoList.add(b);
    }

    @PostMapping("/addPets")
    public ModelMap addPets()
    {
        ModelMap mmap = new ModelMap();
        mmap.put("nameList", cangkuService.selectCangkuAll());

        return mmap;
    }
}
